import os
from utils import doc_util, json_util, read_config
from database.mysqlhelper import MySqLHelper

db = MySqLHelper()
config_path = os.path.join(read_config.data_path, 'common', 'config')

insert_sql = 'insert into t_user_config (f_code,f_name,f_exchange,f_total_hand,f_total_val,f_cir_val) VALUES (%s, %s, %s, %s, %s, %s) '
select_sql = 'select f_code,f_name,f_exchange,f_total_hand,f_total_val,f_cir_val from t_stock_info '


# 初始化所有股票
def insert(stock_info):
    li = ((stock_info['code'], stock_info['name'], stock_info['exchange'], 0, 0))
    return db.insertone(insert_sql, li)


# 初始化所有股票
def insertall():
    stock_dict = doc_util.get_a_doc_dict(os.path.join(config_path, '0.股票信息'), 'code')
    # 增加多条
    li = []
    for key in stock_dict:
        stock_info = json_util.to_json(stock_dict[key])
        li.append((stock_info['code'], stock_info['name'], stock_info['exchange'], 0, 0))
    return db.insertmany(insert_sql, li)


# 所有股票
def selectall():
    return format_res(db.selectall(select_sql))


# 获取一条
def selectone(code):
    # 增加多条
    sql = select_sql + ' where f_code = %s '
    return format_one(db.selectone(sql, (code)))


# 所有股票
def update_the_val(code, total_val, cir_val):
    sql1 = 'update t_stock_info set f_total_val = %s,f_cir_val = %s where f_code = %s  '
    return db.update(sql1, (total_val, cir_val, code))


# 格式化结果
def format_res(res):
    list = []
    for p in res:
        list.append(format_one(p))
    return list


# 格式化结果
def format_one(res):
    if not res:
        return {}
    return {'code': str(res[0], encoding="utf-8"), 'name': str(res[1], encoding="utf-8"), 'exchange': int(res[2]),
            'total_hand': float(res[3]), 'total_val': int(res[4]), 'cir_val': int(res[5])}
